module FindStacks
  
  # Take a pair of files and see if they match. If matched return a stack name.
  def stack_match?(file1,file2,regexps,index)
    results = ''
    regexps.each do | regexp | 
      r = Regexp.new(regexp)
      all1,t1,vol1,ign1,ext1 = r.match(file1.slice(index,file1.size)).to_a
      all2,t2,vol2,ign2,ext2 = r.match(file2.slice(index,file2.size)).to_a
      next if all1.nil?
      next unless t1 == t2 && ext1 == ext2
      if vol1 == vol2  
        index = index + t1.to_s.size + vol1.to_s.size 
        results = stack_match?(file1,file2,[regexp],index)
      elsif ign1 == ign2 
        title = (file1.slice(0,index)).concat(t1)
        break results = "#{title}#{ign1}#{ext1}"
      end
    end  
    return results
  end
  
  # Iterrate through the list of files.
  # Return a filename if single or a Hash (stack_name => file1, file2..) if not.
  def find_stacks(files,res)
  # regexp definitions
    movie_stack_regexps = [
    '(.*?)([ ._-]*[a-d])(.*?)(\.[^.]+)$',
    #<cd/dvd/part/pt/disk/disc/d> <0-N> 
    '(.*?)([ _.-]*(?:cd|dvd|p(?:ar)?t|dis[ck]|d)[ _.-]*[0-9]+)(.*?)(\.[^.]+)$',
    #<cd/dvd/part/pt/disk/disc/d> <a-d> 
    '(.*?)([ _.-]*(?:cd|dvd|p(?:ar)?t|dis[ck]|d)[ _.-]*[a-d])(.*?)(\.[^.]+)$',
    # movienamea-xvid.avi, movienameb-xvid.avi 
  ]
    stack = Hash.new
    f1 = files.shift
    files.each do |f2|
      stack_name = stack_match?(f1,f2,movie_stack_regexps,0)
      unless stack_name.length == 0
        (stack[stack_name] ||= []) << f1 unless stack.has_key?(stack_name)
        stack[stack_name] << f2
      end
    end 
    stack.empty? ? res.push(f1) : res.push(stack)
    files =  files - stack.values.flatten
    files.length > 1 ? res = find_stacks(files,res) : res
  end
  # hide recursion away..
  def list(files)
    res = Array.new
    res = find_stacks(files.sort,[]) 
  end

end

  

# =-=-=-=-=-=-=-=-=- below is for debugging/testing only =-=-=-=-=-=-=-=
#files = %w[vesna_na_zarechnoiparta_parta.avi vesna_na_zarechnoiparta_partb.avi]

#files = %w[ maovienamea-xvid.avi maovienameb-xvid.avi ]
include FindStacks

#p files_and_stacks = FindStacks::list(files)
#p files_and_stacks.class



